package com.db.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

public class Client {
	private static String lastMessage;
	private final static Logger logger = Logger.getLogger(Client.class.getName());
    public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
    	try {
    	    Socket socket = new Socket("localhost", 90);
    	    final long delay = 10000;
    	    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    	    PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
    	    Map<String, String> map = new HashMap<String, String>();
    	    if (!(startGetMap(input, map, output))) {
    	    	Thread.sleep(delay);
    	    	if (!(startGetMap(input, map, output))) {
    	    		socket.close();
    	    	}
    	    }
		    long time1 = System.currentTimeMillis();
		    long time2;
		    String inputString;
		    while(true) {
		    	inputString = input.readLine();
			    if (inputString != null) {
			    	if (inputString.equals("UpdateMap")) {
			    		startGetMap(input, map, output);
			    	} else {
				        time1 = System.currentTimeMillis();
				        logger.info("Server is alive");
			    	}
			    }
			    time2 = System.currentTimeMillis();
			    if ((time2 - time1) > delay) {
				    logger.info("Server seems down");
			    }
		   }
        } catch (SocketException e) {
    	   logger.info("Server seems down");
        }
    }
    
    private static boolean startGetMap(BufferedReader input, Map<String, String> map, PrintWriter output) throws IOException {
    	String readString = input.readLine();
	    String[] readArray = null;
	    while ((readString != null)) {
		    readArray = readString.split(" ");
		    if (readArray[0].equals("0")) {
			    break;
		    }
		    map.put(readArray[0], readArray[1]);
		    lastMessage = readArray[2];
		    readString = input.readLine();
	    }
	    output.write(lastMessage+'\n');
	    output.flush();
	    printMap(map);
	    if (map.isEmpty()) {
	    	return false;
	    } else {
	    	return true;
	    }
    }
    
    private static void printMap(Map<String, String> map) {
    	Iterator<Entry<String, String>> iter = map.entrySet().iterator();
    	Entry<String, String> next;
    	while (iter.hasNext()) {
    		next = iter.next();
    		logger.info("key = "+next.getKey()+" value = "+next.getValue());
    	}
    }
}
